package com.itheima.reggie.common;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RequestMapping("/common")
@RestController
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件名后缀
        String s1 = originalFilename.substring(originalFilename.indexOf("."));

        //通过UUID重新声明文件名, 文件名称重复造成文件覆盖
        String s = UUID.randomUUID().toString();

        String fileName = s + s1;
        //创建一个目录对象
        File file1 = new File(basePath );

        // 判断是否存
        if (!file1.exists()) {
            file1.mkdirs();
        }
        // 将临时文件转存到固定位置
        try {
            file.transferTo(new File(basePath  + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

    @GetMapping("/download")
    public void down(String name, HttpServletResponse response) {

        try {
            //   1). 定义输入流，通过输入流读取文件内容
            FileInputStream  fileInputStream = new FileInputStream(new File(basePath + name));
            //  2). 通过response对象，获取到输出流
            ServletOutputStream outputStream = response.getOutputStream();
            ///   3). 通过response对象设置响应数据格式(image/jpeg)
            response.setContentType("image/jpeg");

            //  4). 通过输入流读取文件数据，然后通过上述的输出流写回浏览器
            int len =0;
            byte[] bytes =new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                //刷新
                outputStream.flush();
            }
            //  5). 关闭资源
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
